if(!window["MUI"]) window["MUI"]={};
// Javascript event delegation

/**
 * MUI.delegate(rules as array of selector,
 * 		event type as string,
 * 		listener as function that gets event object as parameter
 * 		)
 */

MUI.delegate = function(){
    
    var events = {};
    
    /**
     * Checks if the selector point to the Element
     */
    function match(element, selector){
	return $$(selector).contains(element);
    }    
    
    /**
     * The delegation function, get the event type (click, focus, etc...)
     * and returns an event listener that check the elements versus the event type's selectors
     */
    function _delegate(type){
	return function(event){
	    var target = event.target;
	    events[type].each(function(item){
		if(match(target, item["rule"])){
		    item["fn"].apply(target, [event]);
		}
	    })
	}
    }
    
    return function(rules, type, listener){
	rules = $type(rules)=='array'?rules:[rules];
	if(!events[type]){
	    events[type]=[];
	    document.addEvent(type, _delegate(type));
	}
	rules.each(function(rule){
	    events[type].push({rule:rule, fn:listener});
	});
    }
    
}();
